import IP2Region from 'ip2region';

/**
 * 去除对象的空值属性
 * @param obj
 */
export async function removeEmptyP(obj) {
  Object.keys(obj).forEach((key) => {
    if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') {
      delete obj[key];
    }
  });
}

/**
 * 线程阻塞毫秒数
 * @param ms
 */
export function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

/**
 * 获取客户端IP地址
 * @param req
 */
export function getClientIp(req) {
  return (
    req.headers['x-forwarded-for'] ||
    req.ip ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress ||
    ''
  );
}

/**
 * 直接获取的IPV4地址，如果获取到的是IPV6，则通过字符串的截取来转换为IPV4地址。
 * @param ip
 */
export function ipv6ToV4(ip) {
  if (ip.split(',').length > 0) {
    ip = ip.split(',')[0];
  }
  ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
  return ip;
}

/**
 * 查询ip地址
 * @param ip
 */
export function queryIpAddr(ip = '127.0.0.1') {
  const query = new IP2Region();
  return query.search(ip);
}
